package com.kami.leetcode.code_202301;

public class Print {
    public int idx;
    public static void main(String[] args) {
        Object lock = new Object();
        Print p = new Print();
        p.idx = 1;
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    synchronized (lock){
                        try {
                            while (p.idx  != 1){
                                lock.wait();
                            }
                            System.out.println(p.idx);
                            p.idx = 2;
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }finally {
                            lock.notifyAll();
                        }
                    }
                }

                }

        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    synchronized (lock){
                        try {
                            while (p.idx  != 2){
                                lock.wait();
                            }
                            System.out.println(p.idx);
                            p.idx=3;
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }finally {
                            lock.notifyAll();
                        }
                    }
                }

            }

        });
        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    synchronized (lock){
                        try {
                            while (p.idx != 3){
                                lock.wait();
                            }
                            System.out.println(p.idx);
                            p.idx = 1;
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }finally {
                            lock.notifyAll();
                        }
                    }
                }

            }

        });
        thread1.start();
        thread2.start();
        thread3.start();
        while (true){

        }
    }
}
